from sqlalchemy.orm import Session
from config import get_db
from user_dao import (
    init_db, create_user, get_user_by_username,
    update_user, get_users, search_users, delete_user
)
def main():
    # 初始化数据库表
    init_db()
    print("数据库表初始化完成")
    # 获取数据库会话
    db = next(get_db())
    try:
        # 1. 创建新用户
        user = create_user(
            db,
            username="yx_new",
            email="yx_new@www.com",
            hashed_password="secure_hash_here",
            full_name="远方的音讯"
        )
        print(f"创建用户: {user}")

        # 2. 查询用户
        found_user = get_user_by_username(db, "yx")
        print(f"查询到用户: {found_user.to_dict()}")

        # 3. 更新用户信息
        updated_user = update_user(db,
                                   found_user.id,
                                   is_admin=True,
                                   full_name="远方的音讯")
        print(f"更新后用户: {updated_user.to_dict()}")

        # 4. 搜索用户
        search_results = search_users(db, "yx")
        print(f"搜索结果: {[u.username for u in search_results]}")

        # 5. 分页查询用户
        users = get_users(db, skip=0, limit=5)
        print(f"用户列表: {[u.username for u in users]}")

        # 6. 删除用户（实际使用时请谨慎）
        # deleted_user = delete_user(db, found_user.id)
        # print(f"删除用户: {deleted_user}")

    except Exception as e:
        print(f"操作出错: {str(e)}")
        db.rollback()  # 出错时回滚事务
    finally:
        db.close()


if __name__ == "__main__":
    main()
